import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Button, 
  message, 
  Typography, 
  Divider, 
  Row, 
  Col,
  Avatar,
  Space,
  Statistic
} from 'antd';
import { 
  UserOutlined, 
  MailOutlined, 
  LockOutlined,
  EditOutlined,
  SaveOutlined,
  ShoppingOutlined,
  BookOutlined
} from '@ant-design/icons';
import { authApi, userApi, orderApi } from '../../api';

const { Title, Text } = Typography;

const Profile = () => {
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState(false);
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [userInfo, setUserInfo] = useState(null);
  const [stats, setStats] = useState({
    totalOrders: 0,
    totalBooks: 0,
    totalAmount: 0
  });

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const currentUser = authApi.getCurrentUser();
      if (currentUser) {
        setUserInfo(currentUser);
        form.setFieldsValue({
          username: currentUser.username,
          email: currentUser.email
        });
      }
    } catch (error) {
      console.error('获取用户信息错误:', error);
    }
  };

  // 获取用户统计信息
  const fetchUserStats = async () => {
    try {
      // 获取用户的购书统计
      const response = await orderApi.getUserBookStatistics();
      if (response.success) {
        setStats({
          totalOrders: response.data.totalOrders || 0,
          totalBooks: response.data.totalBooks || 0,
          totalAmount: response.data.totalAmount || 0
        });
      }
    } catch (error) {
      console.error('获取用户统计错误:', error);
      // 设置默认值
      setStats({
        totalOrders: 0,
        totalBooks: 0,
        totalAmount: 0
      });
    }
  };

  useEffect(() => {
    fetchUserInfo();
    fetchUserStats();
  }, []);

  // 更新用户信息
  const handleUpdateProfile = async (values) => {
    setLoading(true);
    try {
      const response = await userApi.updateProfile({
        username: values.username,
        email: values.email
      });
      
      if (response.success) {
        message.success('个人信息更新成功');
        setEditing(false);
        // 更新本地存储的用户信息
        const updatedUser = { ...userInfo, ...values };
        setUserInfo(updatedUser);
        authApi.setCurrentUser(updatedUser);
      } else {
        message.error(response.message || '更新失败');
      }
    } catch (error) {
      console.error('更新用户信息错误:', error);
      message.error('更新失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 修改密码
  const handleChangePassword = async (values) => {
    setLoading(true);
    try {
      const response = await userApi.changePassword({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword
      });
      
      if (response.success) {
        message.success('密码修改成功');
        passwordForm.resetFields();
      } else {
        message.error(response.message || '密码修改失败');
      }
    } catch (error) {
      console.error('修改密码错误:', error);
      message.error('密码修改失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditing(false);
    form.setFieldsValue({
      username: userInfo?.username,
      email: userInfo?.email
    });
  };

  return (
    <div>
      <Title level={2}>个人中心</Title>
      
      <Row gutter={16}>
        {/* 左侧：用户信息 */}
        <Col xs={24} lg={16}>
          <Card title="个人信息" style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 24 }}>
              <Avatar 
                size={80} 
                icon={<UserOutlined />}
                style={{ marginRight: 16 }}
              />
              <div>
                <Title level={4} style={{ margin: 0 }}>
                  {userInfo?.username}
                </Title>
                <Text type="secondary">{userInfo?.email}</Text>
              </div>
            </div>

            <Divider />

            <Form
              form={form}
              layout="vertical"
              onFinish={handleUpdateProfile}
              disabled={!editing}
            >
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    name="username"
                    label="用户名"
                    rules={[
                      { required: true, message: '请输入用户名' },
                      { min: 3, message: '用户名至少3个字符' }
                    ]}
                  >
                    <Input prefix={<UserOutlined />} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    name="email"
                    label="邮箱"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input prefix={<MailOutlined />} />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Card>

          {/* 修改密码 */}
          <Card title="修改密码">
            <Form
              form={passwordForm}
              layout="vertical"
              onFinish={handleChangePassword}
            >
              <Form.Item
                name="oldPassword"
                label="当前密码"
                rules={[{ required: true, message: '请输入当前密码' }]}
              >
                <Input.Password prefix={<LockOutlined />} />
              </Form.Item>

              <Form.Item
                name="newPassword"
                label="新密码"
                rules={[
                  { required: true, message: '请输入新密码' },
                  { min: 6, message: '密码至少6个字符' }
                ]}
              >
                <Input.Password prefix={<LockOutlined />} />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                label="确认新密码"
                dependencies={['newPassword']}
                rules={[
                  { required: true, message: '请确认新密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('newPassword') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password prefix={<LockOutlined />} />
              </Form.Item>

              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                >
                  修改密码
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </Col>

        {/* 右侧：统计信息 */}
        <Col xs={24} lg={8}>
          <Card title="购书统计" style={{ marginBottom: 16 }}>
            <Row gutter={16}>
              <Col span={24}>
                <Statistic
                  title="订单总数"
                  value={stats.totalOrders}
                  prefix={<ShoppingOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
            </Row>
            <Divider />
            <Row gutter={16}>
              <Col span={24}>
                <Statistic
                  title="购买书籍"
                  value={stats.totalBooks}
                  suffix="本"
                  prefix={<BookOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
            </Row>
            <Divider />
            <Row gutter={16}>
              <Col span={24}>
                <Statistic
                  title="消费总额"
                  value={stats.totalAmount}
                  precision={2}
                  prefix="¥"
                  valueStyle={{ color: '#ff4d4f' }}
                />
              </Col>
            </Row>
          </Card>

          <Card title="快捷操作">
            <Space direction="vertical" style={{ width: '100%' }}>
              <Button 
                type="primary" 
                block 
                onClick={() => window.location.href = '/orders'}
              >
                查看我的订单
              </Button>
              <Button 
                block 
                onClick={() => window.location.href = '/cart'}
              >
                查看购物车
              </Button>
              <Button 
                block 
                onClick={() => window.location.href = '/books'}
              >
                继续购书
              </Button>
            </Space>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Profile; 